package org.goldfish.message_board01.filters;

import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CustomAuthFilter extends jakarta.servlet.http.HttpFilter {
    public static final String ONLINE_USERS = "onlineUsers";
    private List<String> onlineUsers;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        onlineUsers = new ArrayList<>();
        filterConfig.getServletContext().setAttribute(ONLINE_USERS, onlineUsers);
    }

    @Override
    protected void doFilter(
            jakarta.servlet.http.HttpServletRequest request,
            jakarta.servlet.http.HttpServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        HttpSession session = request.getSession(false);
        String servletPath = request.getServletPath();

        // Allow access to login page, registration page, and public resources
        if (servletPath.equals("/") || servletPath.equals("/register")) {
            chain.doFilter(request, response);
            return;
        }
        if(servletPath.contains("js")){
            chain.doFilter(request, response);
            return;
        }

        boolean logged_in = true;
        VERIFY:
        {
            if (session == null) {
                logged_in = false;
                break VERIFY;
            }
            session.setMaxInactiveInterval(300);
            Object obj = request.getSession(false).getAttribute("username");
            if (obj == null) {
                logged_in = false;
                break VERIFY;
            }
            if (!onlineUsers.contains(obj.toString())) {
                logged_in = false;
                break VERIFY;
            }
        }
        if (!servletPath.contains("messages")&&!logged_in) {
            request.getRequestDispatcher("error.jsp").forward(request, response);
            return;
        }
        request.getSession(true).setAttribute("loggedIn", logged_in);
        chain.doFilter(request, response);

    }

    @Override
    public void destroy() {
        // Cleanup code, if needed
    }
}
